package exam;

import java.util.Random;

public class Example2_SaveTakeMoney {

    public static void main(String[] args) {

        Bank bank = new Bank();
        Random random = new Random();

        //创建了一个存款的线程，并启动
        new Thread(
            () -> {
                while (true){
                    try {
                        bank.saveMoney(random.nextInt(1000)+1);
                        Thread.sleep(500);
                    } catch (InterruptedException e) {
                        throw new RuntimeException(e);
                    }
                }
            }
        ).start();

        //创建了一个取款的线程，并启动
        new Thread(
            () -> {
                while (true){
                    try {
                        bank.takeMoney(random.nextInt(1000)+1);
                        Thread.sleep(500);
                    } catch (InterruptedException e) {
                        throw new RuntimeException(e);
                    }
                }
            }
        ).start();


    }

}

class Bank{

    //当前账户的余额
    int money;

    /**
     * 存款方法，考虑并发添加同步锁
     * @param money
     */
    public synchronized void saveMoney(int money){

        System.out.println("当前余额为:"+this.money);

        //存款没有限制
        this.money += money;

        System.out.println("存了"+money+"元，现余额为:"+this.money);

    }

    /**
     * 取款方法，考虑并发添加同步锁
     * @param money
     */
    public synchronized void takeMoney(int money){

        System.out.println("当前余额为:"+this.money);

        if(money > this.money){
            System.out.println("要取"+money+"元，余额不足");
        }else{
            this.money -= money;
            System.out.println("取了"+money+"元，现余额为:"+this.money);
        }
    }
}